package com.zhugang.week05;

import java.util.HashSet;
import java.util.Set;

/**
 * @program algorithms
 * @description: cycleListNode
 * @author: chanzhugang
 * @create: 2022/07/08 14:16
 */
public class CycleListNode {

    /**
     * 141 环形链表
     *
     * @param head
     * @return
     */
    public boolean hasCycle(ListNode head) {
        // 遍历链表，节点存入哈希表，如果哈希表中存在该节点，表示有环
        Set<ListNode> set = new HashSet<>();
        ListNode p = head;
        while (p != null) {
            if (set.contains(p)) {
                return true;
            }
            set.add(p);
            p = p.next;
        }
        return false;
    }

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}